<template>
    <a-tabs v-model:activeKey="activeKey" type="card">
      <a-tab-pane key="1" tab="设计" style="height: 100vh;">
        <DesignView :xml="xml" :taskList="taskList" :connectionList="connectionList"></DesignView>
      </a-tab-pane>
      <!-- <a-tab-pane key="2" tab="流程数据"  force-render style="height: 100vh;">
        <a-tabs v-model:activeKey="flowActiveKey">
          <a-tab-pane key="s1" tab="流程变量" style="height: 100vh">
            <flowVariables></flowVariables>
          </a-tab-pane>
          <a-tab-pane key="s2" tab="临时变量" force-render>
            <temporaryVariable></temporaryVariable>
          </a-tab-pane>
          <a-tab-pane key="s3" tab="内置表单">
            <formKeys></formKeys>
          </a-tab-pane>
        </a-tabs>
      </a-tab-pane> -->
      <!-- <a-tab-pane key="3" tab="业务方法" style="height: 100vh;">
        <businessMethod></businessMethod>
      </a-tab-pane> -->
      <a-tab-pane key="4" tab="属性" style="height: 100vh;">
        <processProperties></processProperties>
      </a-tab-pane>
      <template #leftExtra>
        <a-button type="text" class="tabs-extra-demo-button" @click="emitEvent" :icon="h(ArrowLeftOutlined)">返回</a-button>
      </template>
      <template #rightExtra>
        <a-button :loading="inputLoading" :icon="h(CloudUploadOutlined)" style="margin-right: 10px;" @click="showModal">导入</a-button>
        <a-button :loading="expLoading" :icon="h(UploadOutlined)" style="margin-right: 10px;" @click="exportBPM">导出</a-button>
        <!-- <a-button type="primary" ghost :loading="saveLoading" :icon="h(HistoryOutlined)" style="margin-right: 10px;" @click="depolyFlow('save')">暂存</a-button> -->
        <a-button :loading="loading" :icon="h(SendOutlined)" style="margin-right: 10px;" type="primary" @click="depolyFlow('depoly')">保存</a-button>
        <a-modal
          title="上传流程JSON文件"
          v-model:open="visible"
          :cancel-button-props="{ disabled: loading }"
          @ok="handleSubmit"
          @cancel="handleCancel"
          :destroyOnClose="true"
        >
          <a-upload
            accept=".json"
            :before-upload="beforeUpload"
            :custom-request="handleCustomRequest"
            :show-upload-list="false"
          >
            <a-button>
              <upload-outlined />
              选择文件
            </a-button>
          </a-upload>
        </a-modal>
        
      </template>
    </a-tabs>
</template>
<script setup lang="tsx">
  import { ref,defineProps,defineEmits,h ,reactive,unref } from 'vue';
  import { Modal } from 'ant-design-vue';
  import DesignView from '@/components/design/designView';
  import flowVariables from '@/components/design/components/FlowPanel/ProcessVariables.vue';
  import formKeys from '@/components/design/components/FlowPanel/FormKeys.vue';
  import temporaryVariable from '@/components/design/components/FlowPanel/TemporaryVariable.vue';
  import processProperties from '@/components/setting/processProperties.vue';
  import businessMethod from '@/components/design/components/FlowPanel/BusinessMethod.vue';  
  import { ArrowLeftOutlined,SendOutlined,HistoryOutlined,UploadOutlined,CloudUploadOutlined,FundProjectionScreenOutlined,ApiOutlined } from '@ant-design/icons-vue';
  import modeler from '@/store/modules/modeler';
  import { deployWithBPMNJS } from '@/api/flow/index';
  import {taskAttr} from '@/store/modules/taskAttr';
  import {gateWayAttr} from '@/store/modules/gateWay';
  import {processInfo} from '@/store/modules/processInfo';
  import { cloneDeep } from 'lodash-es';
  import { connectionAttr } from '@/store/modules/connectionAttr';
  import { businessMethods } from '@/store/modules/businessMethod';
  import { downloadJSON } from '@/components/design/utils/files';
  import { generateRandomString } from '@/utils/common';

  const props = defineProps({
    xml: {
      type: String as PropType<string>,
      default: undefined,
    },
    taskList:{
      type: String as PropType<any>,
      default: undefined,
    },
    connectionList:{
      type: String as PropType<any>,
      default: undefined,
    },
  });
  const visible = ref(false);
  const loading = ref<boolean>(false);
  const inputLoading = ref<boolean>(false);
  const saveLoading = ref<boolean>(false);
  const expLoading = ref<boolean>(false);
  const activeKey = ref('1');
  const flowActiveKey = ref('s1');

  //表单字段列表
  const formKeyList=ref<any>([]);

  const emit = defineEmits(['closeDrawer']);
  const emitEvent = () => {
    Modal.confirm({
      title: '确认要离开吗？',
      content: '当前页面可能有未保存的内容，确定要返回吗？',
      okText: '确定离开',
      cancelText: '取消',
      centered: true,
      closable: true,
      onOk() {
        emit('closeDrawer');
      },
      onCancel() {},
  });
    
  };
  const connectionAttrStore = connectionAttr()
  const businessMethodStore = businessMethods();
  const proceInfoStore=processInfo();
  const gateWayStore=gateWayAttr();
  const taskAttrStore = taskAttr();
  const importRef = ref<HTMLInputElement | null>(null);
  
  //导入
  const importBPM= async()=>{
    const modelerStore = modeler();
    if (importRef.value && importRef.value.stringBPMNXml) {
      console.log(importRef.value.tasksInfo,"importRef.value.tasksInfo1111111111111")
        modelerStore.getModeler!.importXML(importRef.value.stringBPMNXml as string);
         //TODO:方向条件ID重新编码
        const newConnections=importRef.value.connectionsInfo.map(connection => 
          connection.connectionNo="Flow_"+generateRandomString()
        );
        connectionAttrStore.connections=newConnections;
        const sequenceFlowId="Flow_"+generateRandomString();
        //TODO:节点ID重新编码
        const newTasksInfo=importRef.value.tasksInfo.map(taskInfo => 
          taskInfo.TASK_NODE_NO="Activity_"+generateRandomString()
        );
        taskAttrStore.tasks=newTasksInfo;
        //TODO:需要根据选择覆盖、新增，决定id变不变，需要处理key和id
        const newProcInfo=importRef.value.processInfo.procInfo.map(procInfo => 
          procInfo.id="Process_"+Date.now()
        );
        proceInfoStore.procInfo=newProcInfo;
        proceInfoStore.procVariable=importRef.value.processInfo.procVariable;
        //TODO:网关ID重新编码
        const newGateWayInfo=importRef.value.gateWays.map(gateWayInfo => 
          gateWayInfo.GATEWAY_NO="Gateway_"+generateRandomString()
        );
        gateWayStore.gateWays=newGateWayInfo;
        //TODO:网关ID重新编码
        businessMethodStore.bizMethods=importRef.value.methodInfo;
        importRef.value.value = '';
        importRef.value.files = null;
        console.log(taskAttrStore.tasks,"taskAttrStore.tasks1111111111111")
      }
  }
  //导出
  const exportBPM=async()=>{
    expLoading.value=true;
    const xml=await getBPMNData();
    if(xml==""){
      return window.__messageBox.warning('模型加载失败，请刷新重试');
    }
    const taskList=getTaskList();
    const connectionList = getConnectionList();
    
    //导出的数据
    const expData={ 
      stringBPMNXml: xml,//流程模版
      tasksInfo: taskList,//节点列表及配置属性
      connectionsInfo:connectionList,//方向条件列表及配置属性
      processInfo:proceInfoStore,//流程基本信息
      gateWays:gateWayStore.gateWays,//网关列表及配置属性
      methodInfo:businessMethodStore.bizMethods //业务方法列表
    }
    downloadJSON(expData, proceInfoStore.procInfo.name);
    expLoading.value=false;
  }
  //发布
  const depolyFlow = async (type) => {
    if(type=="save"){
      saveLoading.value=true;
      proceInfoStore.setStateData("deployState",0);
    }
    else{
      loading.value=true;
      proceInfoStore.setStateData("deployState",1);
    }
    
    const xml=await getBPMNData();
    if(xml==""){
      return window.__messageBox.warning('模型加载失败，请刷新重试');
    }
    const taskList=await getTaskList();
    const connectionList =await getConnectionList();
    const processInfo={
      procInfo:proceInfoStore.procInfo,
      procVariable:proceInfoStore.procVariable
    }

    const res=await deployWithBPMNJS({ stringBPMNXml: xml,tasksInfo: taskList, connectionsInfo:connectionList,
           processInfo:processInfo,gateWays:gateWayStore.gateWays,methodInfo:businessMethodStore.bizMethods});
    if(type=="save"){
      saveLoading.value=false;
    }
    else{
      loading.value=false;
    }
    if (res.error == '200') {
      window.__messageBox.success('发布成功');
      emit('closeDrawer');
    } else {
      window.__messageBox.error('发布失败');
    }
  };
  //获取流程模版数据
  const getBPMNData= async()=>{
      const modelerStore = modeler();
      try{
        const modeler = modelerStore.getModeler!;
        if (!modeler) {
          return window.__messageBox.warning('模型加载失败，请刷新重试');
        }
        const { error, xml } = await modeler.saveXML({ format: true, preamble: true });
        if (error) {
          console.error(error);
          return "";
        }
        return xml;
      }
      catch (e) {
        window.__messageBox.error((e as Error).message || (e as string));
        return "";
      }
    }
    //获取方向条件设置列表
    const getConnectionList=async()=>{
      const connectionList = cloneDeep(connectionAttrStore.connections);
        for (let i = 0; i < connectionList.length; i++) { 
          if(connectionList[i].expressBody!=""&&connectionList[i].expressBody!=undefined&&connectionList[i].expressBody!=null){
            connectionList[i].expressBody=JSON.stringify(connectionList[i].expressBody);
          }
        }
        return connectionList;
    }
    //获取节点列表
    const getTaskList = () => {
      return cloneDeep(taskAttrStore.tasks).map(task => {
        const boolToNumber = (value) => value ? 1 : 0;
        task.TASK_RUN_AGAIN_REC_PRO = boolToNumber(task.TASK_RUN_AGAIN_REC_PRO);
    
        task.TASK_RUN_DATA_MOD_ALLOW = boolToNumber(task.TASK_RUN_DATA_MOD_ALLOW);
    
        if (task.TASK_RUN_DATA) {
          task.TASK_RUN_DATA = JSON.stringify(task.TASK_RUN_DATA);
        }
    
        return task;
      });
    };
    // 显示弹窗
    const showModal = () => {
      visible.value = true;
    };
    // 文件验证
    const beforeUpload = (file: File) => {
      const isJson = file.type === 'application/json';
      if (!isJson) {
        window.__messageBox.error('仅支持 JSON 文件!');
      }
      return isJson;
    };

    // 自定义上传处理
    const handleCustomRequest = (options: any) => {
      const { file, onSuccess, onError } = options;
        const reader = new FileReader();

        reader.onload = (e) => {
          try {
            const content = JSON.parse(e.target?.result as string);
            importRef.value = content;
            onSuccess();
          } catch (error) {
            window.__messageBox.error('JSON 解析失败');
            onError(error);
          }
        };

        reader.onerror = (error) => {
          window.__messageBox.error('文件读取失败');
          onError(error);
        };

       reader.readAsText(file);
    };
    // 提交处理
    const handleSubmit = async () => {
      try {
        await importBPM();
        window.__messageBox.success('处理成功!');
        visible.value = false;
        resetState();
      } catch (error) {
        window.__messageBox.error('处理失败');
      } 
    };

  // 取消处理
  const handleCancel = () => {
    if (!loading.value) {
      resetState();
    }
  };


  // 重置状态
  const resetState = () => {
    importRef.value = null;
  };
</script>
<style scoped>
  .step-description {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 12px;
  padding: 5px;
}
</style>
  
  